package com.smzd.utils;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.DateFormatUtils;;

public class SimpleDateTimeUtil {
	public static final int FORMAT_INDEX_YMDHMS = 0;
	public static final int FORMAT_INDEX_YMDHM = 1;
	public static final int FORMAT_INDEX_YMD = 2;
	
	private static final String[] fmts = new String[]{
		"yyyy-MM-dd HH:mm:ss",
		"yyyy-MM-dd HH:mm",
		"yyyy-MM-dd",
	};
	
	public static Date parse(String dateStr){
		if(StringUtils.isEmpty(dateStr)){
			return null;
		}
		try {
			return DateUtils.parseDate(dateStr, fmts);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
	public static String formatToDate(Date date){
		return format(date, FORMAT_INDEX_YMD);
	}
	public static String formatToDateTime(Date date){
		return format(date, FORMAT_INDEX_YMDHMS);
	}
	private static String format(Date date, int fmtIdx){
		if(date==null){
			return null;
		}
		if(fmtIdx<0){
			fmtIdx = 0;
		}
		if(fmtIdx>2){
			fmtIdx = 2;
		}
		String fmt = fmts[fmtIdx];
		return DateFormatUtils.format(date, fmt);
	}
	public static String format(Date date, String pattern){
		return DateFormatUtils.format(date, pattern);
	}

}
